import { defineStore } from 'pinia'
import { ref } from 'vue'
import type { RouteLocationNormalizedLoaded } from 'vue-router'

export interface TabItem {
  path: string
  name: string
  title: string
  closable: boolean
}

export const useTabsStore = defineStore('tabs', () => {
  const tabs = ref<TabItem[]>([
    {
      path: '/dashboard',
      name: 'Dashboard',
      title: '首页',
      closable: false
    }
  ])
  
  const activeTab = ref('/dashboard')

  // 添加标签页
  const addTab = (route: RouteLocationNormalizedLoaded) => {
    const existTab = tabs.value.find(tab => tab.path === route.path)
    if (!existTab) {
      tabs.value.push({
        path: route.path,
        name: route.name as string,
        title: route.meta.title as string,
        closable: route.path !== '/dashboard'
      })
    }
    activeTab.value = route.path
  }

  // 移除标签页
  const removeTab = (path: string) => {
    const index = tabs.value.findIndex(tab => tab.path === path)
    if (index !== -1) {
      tabs.value.splice(index, 1)
      
      // 如果关闭的是当前激活的标签，切换到最后一个标签
      if (activeTab.value === path && tabs.value.length > 0) {
        activeTab.value = tabs.value[tabs.value.length - 1].path
        return tabs.value[tabs.value.length - 1].path
      }
    }
    return null
  }

  // 设置当前激活的标签
  const setActiveTab = (path: string) => {
    activeTab.value = path
  }

  // 关闭其他标签
  const closeOtherTabs = (path: string) => {
    tabs.value = tabs.value.filter(tab => tab.path === path || !tab.closable)
    activeTab.value = path
  }

  // 关闭所有标签（除了首页）
  const closeAllTabs = () => {
    tabs.value = tabs.value.filter(tab => !tab.closable)
    activeTab.value = '/dashboard'
  }

  return {
    tabs,
    activeTab,
    addTab,
    removeTab,
    setActiveTab,
    closeOtherTabs,
    closeAllTabs
  }
})

